<template>
  <span style="color: #ff0000; font-weight: 700">{{ min }}分钟{{ sec }}秒</span>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  modelValue: {
    type: Number,
    required: false,
  },
})

const emit = defineEmits(['update:modelValue', 'timeout'])

const leftSeconds = ref(0)
const min = ref('00')
const sec = ref('00')

// 进行倒计时
const countdown = () => {
  // 倒计时结束了
  if (leftSeconds.value < 0) {
    emit('timeout')
    return
  }

  // 分和秒
  const minutes = parseInt(leftSeconds.value / 60)
  const seconds = parseInt(leftSeconds.value % 60)

  min.value = minutes > 9 ? minutes.toString() : '0' + minutes
  sec.value = seconds > 9 ? seconds.toString() : '0' + seconds
  leftSeconds.value -= 1

  setTimeout(countdown, 1000)
}

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newValue) => {
    leftSeconds.value = newValue
    countdown()
  },
  { immediate: true }
)

// 初始化
onMounted(() => {
  leftSeconds.value = props.modelValue
})
</script>
